<template>
  <div>
    <div style="padding: 30px 0">
      <a-form
          layout="inline"
          :model="searchState"
          @finish="searchFinish"
      >
        <a-form-item v-bind="validateInfos.name" label="文献名字">
          <a-input v-model:value="searchState.name" placeholder="请输入查询的名称"/>
        </a-form-item>
        <a-form-item v-bind="validateInfos.grounding">
          <a-select v-model:value="searchState.grounding" style="width: 200px" placeholder="请选择上架状态">
            <a-select-option :value="item.value" v-for="item in selectData" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button
              type="primary"
              html-type="submit"
              style="margin-right: 10px"
          >
            查询
          </a-button>
          <a-button
              style="margin-right: 10px"
              type="primary"
              @click="resetFields"
          >
            重置
          </a-button>
          <a-button
              type="primary"
              @click="createClick"
          >
            新建
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-table :dataSource="dataSource" :columns="columns" bordered :pagination="pagination">
      <template #bodyCell="{column,record}">
        <!-- 操作 -->
        <template v-if="column.key === 'action'">
          <a-button type="primary" style="margin-right: 10px" @click="editClick(record)">编辑</a-button>
          <a-popconfirm
              :title="'是否确定删除'+record.name+'文献?'"
              ok-text="确定"
              cancel-text="取消"
              @confirm="delClick(record.id)"
          >
            <a-button type="primary" danger>删除</a-button>
          </a-popconfirm>
          <a-button type="primary" style="margin-left: 10px" @click="readFileClick(record)">查阅</a-button>
        </template>
        <!-- 封面 -->
        <template v-if="column.key === 'cover_url'">
          <img :src="record.cover_url" alt="" width="50" height="50" style="object-fit: contain">
        </template>
        <!-- 文件类型 -->
        <template v-if="column.key === 'file_url'">
          {{ record.file_url.substring(record.file_url.lastIndexOf(".") + 1) }}
        </template>
        <!-- 是否推荐 -->
        <template v-if="column.key==='recommend'">
          <a-switch :checked="record.recommend>0" @change="(checked:boolean)=>recommendChange(record,checked)"/>
        </template>
        <!-- 是否上架 -->
        <template v-if="column.key==='grounding'">
          <a-switch :checked="record.grounding>0" @change="(checked:boolean)=>groundingChange(record,checked)"/>
        </template>
      </template>
    </a-table>
    <ReadFile :url="currentData?.file_url" :is-show="isShow" :is-mol-file="isMolFile"
              @close="()=>isMolFile = false"/>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, toRaw, watchEffect} from "vue";
import {useForm} from "ant-design-vue/es/form";
import type {ColumnsType} from "ant-design-vue/es/table";
import {LiteratureDataType, PageAdnSizeType} from "@/util/publicType";
import {useRoute, useRouter} from "vue-router";
import {delLiterature, literatureList, literatureUpdateGrounding, literatureUpdateRecommend} from "@/api/api";
import type {AxiosResponse} from "axios";
import {setNullData} from "@/util";
import {message} from "ant-design-vue";
import ReadFile from "@/components/ReadFile.vue";

// 搜索type
interface FormState {
  name: string | null,
  grounding: number | null
}

// 数据
const dataSource = ref<LiteratureDataType[]>([]);
// 路由
const router = useRouter();
// 路由信息
const route = useRoute();
// 当前路由id
const {id} = route.params;
// 当前分类id
const dictId = ref<number>(0);
// 查阅的类型
const isShow = reactive<{ isVideo: boolean, isAudio: boolean }>({isVideo: false, isAudio: false});
// 查阅弹窗
const isMolFile = ref<boolean>(false);
// 当前页和条数
const pageAndSize = reactive<PageAdnSizeType>({
  page: 1,
  size: 15,
});
// 当前name
const name = ref<string | null>(null);
// 当前上架状态
const grounding = ref<number | null>();
// 当前文件
const currentData = ref<LiteratureDataType>();
// 分页
const pagination = ref({
  total: 0,
  current: pageAndSize.page,
  // 默认每页显示条数
  defaultPageSize: pageAndSize.page,
  // 每页条数
  pageSize: pageAndSize.size,
  // 是否快速跳转
  showQuickJumper: true,
  // 是否可以改变page和size
  showSizeChanger: true,
  // 总条数
  showTotal: (total: number) => "总条数：" + total,
  //页码改变或者条数的回调
  onChange: (p: number, ps: number) => {
    pageAndSize.page = p;
    pageAndSize.size = ps;
  },
});
// 下拉
const selectData = reactive<{ label: string, value: number }[]>([
  {
    label: "未上架",
    value: 0
  },
  {
    label: "已上架",
    value: 1
  }
])

// 搜索状态
const searchState = reactive<FormState>({
  name: null,
  grounding: null
});

// 表头
const columns: ColumnsType<LiteratureDataType> = [
  {
    title: "封面",
    dataIndex: "cover_url",
    key: "cover_url",
    align: "center",
  },
  {
    title: "文献名字",
    dataIndex: "name",
    key: "name",
    align: "center",
    width: "18%"
  },
  {
    title: "作者",
    dataIndex: "author",
    key: "author",
    align: "center"
  },
  {
    title: "出版社",
    dataIndex: "press",
    key: "press",
    align: "center"
  },
  {
    title: "文件类型",
    dataIndex: "file_url",
    key: "file_url",
    align: "center",
  },
  {
    title: "阅读数",
    dataIndex: "visit_num",
    key: "visit_num",
    align: "center"
  },
  {
    title: "是否推荐",
    dataIndex: "recommend",
    key: "recommend",
    align: "center",
  },
  {
    title: "是否上架",
    dataIndex: "grounding",
    key: "grounding",
    align: "center",
  },
  {
    title: "文献编号",
    dataIndex: "code",
    key: "code",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
  }
]

const getData = (page: number, size: number, name: string | null = null, grounding: number | null = null) => {
  literatureList(page, size, name, grounding, id as string).then((r: AxiosResponse) => {
    let {data, meta, type_id} = r.data.data;
    pagination.value = {
      ...pagination.value,
      pageSize: meta.perSize,
      total: meta.total,
      current: meta.currentPage,
    };
    // 存储当前字典id
    dictId.value = type_id;
    data = data.map((v: LiteratureDataType) => {
      return {
        ...v,
        cover_url: v.cover.path,
        file_url: v.file.path,
        key: v.id,
        author: setNullData(v.author),
        press: setNullData(v.press),
        code: setNullData(v.code)
      }
    });
    dataSource.value = data;
  }, err => message.error(err))
}

// 请求数据
watchEffect(() => {
  getData(pageAndSize.page, pageAndSize.size, name.value, grounding.value);
})

// 搜索参数
const searchRuleRef = reactive({
  name: [
    {
      required: false,
    }
  ],
  grounding: [
    {
      required: false,
    }
  ]
})

// 获取搜索参数表单事件
const {resetFields, validate, validateInfos} = useForm(searchState, searchRuleRef);

// 搜索完成
const searchFinish = () => {
  validate().then(() => {
    const data = toRaw(searchState);
    name.value = data.name ? data.name : null;
    grounding.value = data.grounding ? data.grounding : null;
  })
}

// 编辑
const editClick = (v: LiteratureDataType) => {
  router.push(`/literature/update/${v.id}`)
}

// 新建
const createClick = () => {
  // dictId是字典类型id，以此获取所有文献分类
  router.push(`/literature/create/${dictId.value}`);
}

// 刪除
const delClick = (id: string) => {
  delLiterature(id).then(() => {
    message.success("删除成功");
    getData(pageAndSize.page, pageAndSize.size, name.value, grounding.value);
  }, err => message.error(err))
}

// 判断文件类型
const isFile = (type: string, url: string) => {
  switch (type) {
    case "pdf":
      isMolFile.value = false;
      return window.open(url);
    case "mp3":
      isMolFile.value = true;
      isShow.isVideo = false;
      return isShow.isAudio = true;
    case "mp4":
      isMolFile.value = true;
      isShow.isVideo = true;
      return isShow.isAudio = false;
    default:
      isMolFile.value = false;
      isShow.isVideo = false;
      return isShow.isAudio = false;
  }
}

// 是否推荐
const recommendChange = (v: LiteratureDataType, checked: boolean) => {
  literatureUpdateRecommend(v.id, {recommend: checked ? 1 : 0}).then(() => {
    message.success(checked ? "文献已推荐" : "文献已取消推荐");
    getData(pageAndSize.page, pageAndSize.size, name.value, grounding.value);
  }, err => message.error(err));
}

// 是否上架
const groundingChange = (v: LiteratureDataType, checked: boolean) => {
  literatureUpdateGrounding(v.id, {grounding: checked ? 1 : 0}).then(() => {
    message.success(checked ? "文献已上架" : "文献已取消上架");
    getData(pageAndSize.page, pageAndSize.size, name.value, grounding.value);
  }, err => message.error(err))
}

// 查阅文件
const readFileClick = (v: LiteratureDataType) => {
  // 保存当前信息
  currentData.value = v;
  // 显示弹窗
  isMolFile.value = true;
  const type = v.file_url.substring(v.file_url.lastIndexOf(".") + 1);
  isFile(type, v.file_url);
}
</script>